<template>
  <el-dialog title="添加题目" v-model="dialogVisible" width="900px" @closed="handleDialogClosed" destroy-on-close :close-on-click-modal="false">
    <div class="selector-container">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <el-input v-model="searchParams.title" placeholder="搜索题目标题..." prefix-icon="Search" clearable class="search-input" @input="handleSearch" />
        <el-select v-model="searchParams.difficulty" placeholder="难度筛选" clearable class="filter-select" @change="handleSearch">
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
      </div>

      <!-- 题目列表 -->
      <div class="problem-list" v-loading="loading">
        <el-table :data="problemList" @selection-change="handleSelectionChange" ref="problemTable" max-height="400">
          <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="title" label="题目标题" min-width="200">
            <template #default="{ row }">
              <div class="problem-title">
                <span>{{ row.title }}</span>
                <el-tag v-if="isProblemInSet(row.id)" type="info" size="small" class="added-tag">已添加</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="难度" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getDifficultyType(row.difficulty)" size="small">
                {{ row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="120" align="center" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next"
            small
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 已选题目区域 -->
      <div class="selected-section" v-if="selectedProblems.length > 0">
        <div class="section-title">已选题目 ({{ selectedProblems.length }})</div>
        <div class="selected-list">
          <div v-for="(problem, index) in selectedProblems" :key="problem.id" class="selected-item">
            <span class="item-index">{{ index + 1 }}.</span>
            <span class="item-title">{{ problem.title }}</span>
            <el-input-number v-model="problem.targetScore" :min="1" :max="1000" size="small" class="score-input" placeholder="分数" />
            <el-button type="danger" link size="small" @click="removeSelected(problem.id)">移除</el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="submitting">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="selectedProblems.length === 0">确认添加 ({{ selectedProblems.length }})</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue"
import { ElMessage } from "element-plus"
import { getProblemList } from "@/api/modules/problem"
import { batchAddProblemsToSet } from "@/api/modules/problem-set"

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  setId: {
    type: Number,
    required: true
  },
  existingProblems: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(["update:visible", "success"])

// 数据定义
const dialogVisible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const problemList = ref([])
const selectedProblems = ref([])
const problemTable = ref(null)

// 搜索参数
const searchParams = reactive({
  title: "",
  difficulty: ""
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 已存在的题目ID集合
const existingProblemIds = computed(() => {
  return new Set(props.existingProblems.map(p => p.problemId || p.id))
})

// 检查题目是否已在题目集中
const isProblemInSet = problemId => {
  return existingProblemIds.value.has(problemId)
}

// 检查是否可选择
const checkSelectable = row => {
  return !isProblemInSet(row.id)
}

// 获取难度标签类型
const getDifficultyType = difficulty => {
  const typeMap = {
    简单: "success",
    中等: "warning",
    困难: "danger"
  }
  return typeMap[difficulty] || ""
}

// 加载题目列表
const loadProblemList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchParams.title,
      difficulty: searchParams.difficulty,
      isAdmin: true // 获取管理员题库
    }

    const response = await getProblemList(params)

    if (response.code === 200) {
      problemList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || "获取题目列表失败")
    }
  } catch (error) {
    console.error("加载题目列表失败:", error)
    ElMessage.error("获取题目列表失败")
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadProblemList()
}

// 分页处理
const handleSizeChange = newSize => {
  pageSize.value = newSize
  currentPage.value = 1
  loadProblemList()
}

const handleCurrentChange = newPage => {
  currentPage.value = newPage
  loadProblemList()
}

// 选择变化处理
const handleSelectionChange = rows => {
  // 合并新选择的题目，保留已有的配置
  const existingMap = new Map(selectedProblems.value.map(p => [p.id, p]))

  selectedProblems.value = rows.map(row => {
    if (existingMap.has(row.id)) {
      return existingMap.get(row.id)
    }
    return {
      id: row.id,
      title: row.title,
      targetScore: 100 // 默认分数
    }
  })
}

// 移除已选题目
const removeSelected = problemId => {
  selectedProblems.value = selectedProblems.value.filter(p => p.id !== problemId)

  // 同时取消表格中的选择
  if (problemTable.value) {
    const row = problemList.value.find(p => p.id === problemId)
    if (row) {
      problemTable.value.toggleRowSelection(row, false)
    }
  }
}

// 提交添加
const handleSubmit = async () => {
  if (selectedProblems.value.length === 0) {
    ElMessage.warning("请至少选择一个题目")
    return
  }

  submitting.value = true
  try {
    // 构建提交数据
    const problems = selectedProblems.value.map((problem, index) => ({
      problemId: problem.id,
      sortOrder: null, // 让后端自动生成
      targetScore: problem.targetScore || 100
    }))

    // 批量添加
    await batchAddProblemsToSet(props.setId, problems)

    ElMessage.success(`成功添加 ${problems.length} 个题目`)
    dialogVisible.value = false
    emit("success")
  } catch (error) {
    console.error("添加题目失败:", error)
    ElMessage.error(error.message || "添加题目失败")
  } finally {
    submitting.value = false
  }
}

// 对话框关闭处理
const handleDialogClosed = () => {
  // 重置数据
  selectedProblems.value = []
  searchParams.title = ""
  searchParams.difficulty = ""
  currentPage.value = 1
  problemList.value = []

  emit("update:visible", false)
}

// 监听visible变化
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal
    if (newVal) {
      loadProblemList()
    }
  },
  { immediate: true }
)

// 监听dialogVisible变化
watch(dialogVisible, newVal => {
  if (props.visible !== newVal) {
    emit("update:visible", newVal)
  }
})
</script>

<style lang="scss" scoped>
@use "@/styles/base/variables" as *;

.selector-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-section {
  display: flex;
  gap: 12px;

  .search-input {
    flex: 1;
  }

  .filter-select {
    width: 150px;
  }
}

.problem-list {
  .problem-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .added-tag {
      flex-shrink: 0;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    padding: 16px 0 8px;
  }
}

.selected-section {
  border-top: 1px solid $border-color-lighter;
  padding-top: 16px;

  .section-title {
    font-size: 14px;
    font-weight: 600;
    color: $color-text-primary;
    margin-bottom: 12px;
  }

  .selected-list {
    max-height: 200px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .selected-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: $bg-color-layout;
    border-radius: $border-radius-base;
    border: 1px solid $border-color-lighter;

    .item-index {
      font-weight: 600;
      color: $color-text-secondary;
      min-width: 24px;
    }

    .item-title {
      flex: 1;
      font-size: 14px;
      color: $color-text-primary;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .score-input {
      width: 120px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  :deep(.el-button) {
    // 确保按钮使用 Element Plus 的默认样式
    // 不覆盖任何颜色
  }
}
</style>
